package com.cjx.print.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cjx.print.App;
import com.cjx.print.BackgroundService;
import com.cjx.print.R;
import com.cjx.print.utils.SPUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * create by cjx on 2024/9/6
 * desc:
 */
public class MainActivityOld extends AppCompatActivity {

    private final int REQUEST_PERMISSION_CODE = 1000;
    private final String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,};

    TextView modeView;
    TextView typeView;
    TextView connectView;
    ProgressBar progressBar;
    View modeContainer;
    View typeContainer;

    private int currentMode;
    private int currentType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_old);

        ArrayList<String> permissions = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (!permissions.isEmpty()) {
                requestPermissions(permissions.toArray(new String[0]), REQUEST_PERMISSION_CODE);
            } else {
                init();
            }
        } else {
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            boolean flagt = false;
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flagt = true;
                    break;
                }
            }
            if (flagt) {//授权失败
                finish();
            } else {
                init();
            }
        }
    }

    private void init() {
        connectView = findViewById(R.id.connect);
        progressBar = findViewById(R.id.progress);
        modeView = findViewById(R.id.mode);
        typeView = findViewById(R.id.type);
        modeContainer = findViewById(R.id.mode_container);
        typeContainer = findViewById(R.id.type_container);

        modeContainer.setSelected(true);
        currentMode = SPUtils.getInt(App.SP_MODE, 1);
        currentType = SPUtils.getInt(App.SP_TYPE, 1);
        if (currentMode == 0) {
            modeView.setText("精臣 B3S系列");
            typeView.setText("蓝牙");
            typeContainer.setSelected(false);
            typeContainer.setEnabled(false);
        } else {
            modeView.setText("芯烨 XP-T271U");
            typeContainer.setSelected(true);
        }
        typeView.setText(currentType == 0 ? "蓝牙" : "USB");
        modeContainer.setOnClickListener(v -> {
            SingleSelectDialogFragment.newInstance("选择打印机", getPrinterItems(), item -> {
                modeView.setText(item.name);
                currentMode = Integer.parseInt(item.key);
                if (currentMode == 0) {
                    currentType = 0;
                    typeView.setText("蓝牙");
                    typeContainer.setSelected(false);
                    typeContainer.setEnabled(false);
                } else {
                    typeContainer.setSelected(true);
                    typeContainer.setEnabled(true);
                }
            }).show(getSupportFragmentManager(), "mode");
        });
        typeContainer.setOnClickListener(v -> {
            SingleSelectDialogFragment.newInstance("连接方式", getTypeItems(), item -> {
                typeView.setText(item.name);
                currentType = Integer.parseInt(item.key);
            }).show(getSupportFragmentManager(), "type");
        });
        connectView.setOnClickListener(v -> {
            connectView.setText(null);
            connectView.setEnabled(false);
            progressBar.setVisibility(View.VISIBLE);
            startService();
        });

        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).observe(this, o -> {
            if (o == null || !o) {
                connectView.setText("连接");
                connectView.setEnabled(true);
                progressBar.setVisibility(View.GONE);
            } else {
                SPUtils.putInt(App.SP_MODE, currentMode);
                SPUtils.putInt(App.SP_TYPE, currentType);
                Toast.makeText(MainActivityOld.this, "连接成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private List<SingleSelectDialogFragment.ItemEntity> getPrinterItems() {
        return Arrays.asList(
                new SingleSelectDialogFragment.ItemEntity("精臣 B3S系列", "0", null),
                new SingleSelectDialogFragment.ItemEntity("芯烨 XP-T271U", "1", null)
        );
    }

    private List<SingleSelectDialogFragment.ItemEntity> getTypeItems() {
        return Arrays.asList(
                new SingleSelectDialogFragment.ItemEntity("蓝牙", "0", null),
                new SingleSelectDialogFragment.ItemEntity("USB", "1", null)
        );
    }

    private void startService() {
        System.out.println("MainActivity 启动后台服务");
        Intent severIntent = new Intent(this, BackgroundService.class);
        severIntent.putExtra("mode", currentMode);
        severIntent.putExtra("type", currentType);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(severIntent);
        } else {
            startService(severIntent);
        }
    }


}
